import app, { xlsxCfgNames } from "../../app";
import god from "../../god";
import manage_user from "../../master/model/manage/manage_user";
import { group, rank_type, taskKey } from "../../shared/interface";
import { Tpl_battleEnd, template } from "../../shared/master/MsgAction";
import { baseCalss } from "../base/baseCalss";
import battlefield from "../fight/battle/battlefield";
import { baseBody } from "../fight/body/baseBody";
import { calls } from "../fight/body/calls";
import { enemy } from "../fight/body/enemy";
import { pet } from "../fight/body/pet";
import { player } from "../fight/body/player";
import { SKILL } from "../fight/skill/SK_active";
import { logger } from "../server/logger";
import manage_task from "../../master/model/manage/manage_task";
import word from "./word";

export class wordBoss extends baseCalss {
    nextShowTime: number = Date.now() + 60000 * 5;
    battles: battlefield | undefined;
    bossUnit: enemy | undefined;
    bossTable: Map<string, any> = new Map();
    _parent: word;
    constructor(table: Map<any, any> | undefined, parent: word) {
        super()
        if (table) {
            this.bossTable = table;
        }
        this._parent = parent;
    }
    getWord() {
        return this._parent
    }
    // 销毁世界
    destroy() {
        this.battles?.destroy();
        this.bossUnit?.destroy();
        super.destroy();
    }
    check() {
        return;
        // if (!this.bossTable.size) {
        //     return;
        // }
        // if (this.nextShowTime > Date.now()) {
        //     console.log('boss 时间未到')
        //     return;
        // }
        // this.nextShowTime = Date.now() + 60000 * 5;
        // if (this.battles || this.bossUnit && !this.bossUnit.is_die()) {
        //     return;
        // }
        // this.createBoss();

        // if (!this.bossUnit) {
        //     return;
        // }
        // const wordName = this._parent.name;
        // manage_user.sendAllMsg(template.default, `BOSS出现:${this.bossUnit.name}Lv.${this.bossUnit.leve.num}`)
    }
    createBoss() {
        let w = this.getWord();
        let leve = this._parent.getAverageleve();
        let e = app.createUnity('-1', app.random(leve, leve*2), this.bossTable, app.random(w.cfg.fallScoreMax * 2, w.cfg.fallScoreMax * 5)) as enemy;
        e.P.Hp_Max += app.random(leve, leve*2) * 10000;
        if (!this.battles) {
            this.battles = new battlefield();
            this.battles.setSpecial(true);
            this.battles.setRoundTime(5);
        }
        e.setWord(this._parent);
        e.name = `${this._parent.name}-世界Boss`
        for (let i = 0; i < 5; i++) {
            const table = app.xlsxCfgMap.get(xlsxCfgNames.召唤表) as Map<string, any>;
            let body = app.createUnity('-1', app.random(e.leve.num, e.leve.num*1.2), table, app.random(w.cfg.fallScoreMax, w.cfg.fallScoreMax), 2) as pet;
            e.addPet(body)
        }

        this.bossUnit = e;
        this.battles.join(e, group.主场);
        console.log('------boss 已诞生');

    }
    private onBattleOutEnd(endBattle: battlefield, outBody: baseBody) {
        let allBody = endBattle.getBody_all();
        outBody.del_battle();
        // 释放战场
        for (let i = 0; i < allBody.length; i++) {
            const element = allBody[i];
            element.del_battle();
        }
    }
    /**
     * 战斗结束
     * 需要知道哪方胜利
     * 需要知道奖励是什么， 具体数量
     */
    private onBattleEnd(endBattle: battlefield, winGroup: group) {
        // TODO:BOSS战补全
        console.log(`战场:${endBattle.id},${winGroup}方胜利`);

        let allBody = endBattle.getBody_all();
        let winBodys = endBattle.getBody_all_group(winGroup);
        let dieBodys = endBattle.getBody_all_group(app.getAbsGroup(winGroup));
        // 消息推送模板
        let obj: Tpl_battleEnd = {
            round: endBattle.round,
            winGroup: winGroup,
            gifts: []
        }
        // 奖励分配
        /**
         * 怪物死亡 掉落金币 钻石
         * 所有胜利方玩家均分 金币
         * 玩家死亡 掉落金币 钻石
         */
        let gold = 0;
        let diamond = 0;
 
        // 所有胜利方玩家均分 金币
        let winPlayers: player[] = [];
        let winExpBodys: baseBody[] = []
        for (let index = 0; index < winBodys.length; index++) {
            const element = winBodys[index];
            if (element instanceof player) {
                winPlayers.push(element)
                winExpBodys.push(element);
            }
        }
        let exp = 0;
        for (let index = 0; index < dieBodys.length; index++) {
            const element = dieBodys[index];
            if (element instanceof enemy) {
                gold += element.leve.num * winPlayers.length;
                exp += element.leve.num * god.getServerCfgItem('leve_exp_base').b * winPlayers.length;
            }
        }
        let avGold = Math.ceil(gold / winPlayers.length);
        let avExp = Math.ceil(exp / winExpBodys.length);

        winExpBodys.forEach(element => {
            element.addExp(avExp);
        })
        winPlayers.forEach(element => {
            obj.gifts.push({ user_id: element.uuid, user_name: element.name, info: { gold: avGold, diamond: diamond, exp: avExp } })
        });


        for (let i = 0; i < allBody.length; i++) {
            const element = allBody[i];
            if (element instanceof player) {
                element.sendMsg(template.Battle_end, obj);
            }
        }

        if (winGroup == group.主场) {
            endBattle.destroy();
            this.battles = undefined;
        }
        // 释放战场
        if (winGroup == group.客场) {
            endBattle.destroy();
            this.nextShowTime = 60 * 1000 * 5;
            this.bossUnit = undefined;
            this.battles = undefined;
        }
    }
    /**
     * 监听单位击杀情况
     * @param idx 
     * @returns 
     */
    private onBattleKill(battle: battlefield, winBody: baseBody, dieBody: baseBody, sk: SKILL) {
        let _winBody = winBody.get_Master()
        // TODO:详细分析
        manage_task.event(taskKey.击杀普通怪物, 1, winBody, dieBody)
        dieBody.get_battle()?.addRoundLog(
            dieBody.get_Master().uuid, `☠️${dieBody.name}`,
            winBody.name,
            []
        )
        if (_winBody instanceof player) {
            if (dieBody instanceof enemy) {
                let exp = app.random(dieBody.leve.num * 1000, dieBody.leve.num * 2000);
                _winBody.addExp(exp);
                // 掉落金币还是道具
                const cfg = god.getServerCfgItem('boss_kill_gift')
                let item = app.createCfgItem(cfg.a, app.random(dieBody.leve.num, dieBody.leve.num * 1.5), '世界BOSS击杀奖励');
                item.cont_change(app.random(0, cfg.b))
                _winBody.log.add(rank_type.boss击杀次数, 1)
                _winBody.get_battle()?.addRoundLog(
                    _winBody.uuid,
                    winBody.name,
                    `☠️${dieBody.name}`,
                    [
                        { name: '⏳经验', cont: exp },
                        { name: `${item.getStyleName()}`, cont: 1 }
                    ]
                )
                this.nextShowTime = Date.now() + 60000 * 5;
                manage_user.sendAllMsg(template.default,`恭喜${_winBody.name}击杀了${dieBody.name}！！获得${item.getStyleName()}`)
                _winBody.getBag().add(item);
            }
        }
        if (dieBody instanceof calls) {
            battle.out(dieBody)
        }
    }
    private onBattleRound(battle: battlefield, group: Map<string, baseBody>[]) {
        let giftMap: Map<string, { player: player }> = new Map()
        for (let i = 0; i < group.length; i++) {
            const element = group[i];
            element.forEach(e => {
                if (e instanceof enemy) {
                    return;
                }
                if (e instanceof player) {
                    if (e.is_die()) {
                        return;
                    }

                    giftMap.set(e.uuid, { player: e })
                }
            });
        }
        giftMap.forEach(element => {
            let item = app.createCfgItem('prop-7', 0, '世界BOSS回合奖励');
            element.player.getBag().add(item);
            element.player.sendMsg(template.default, `BOSS战回合存活${item.getStyleName()}`)
        });
    }
    attack(active: player) {
        if (!this.battles || !this.bossUnit) {
            active.sendMsg(template.default, `当前世界boss暂未出现.等待下次出现`)
            return;
        }

        if ((this.bossUnit as enemy).is_die()) {
            active.sendMsg(template.default, `当前世界boss已死亡.等待下次出现`)
            return;
        }
        let battle = active.get_battle();
        if (battle) {
            if (battle.id == this.battles.id) {
                this.battles.join(active, group.客场);
                this.battles.start();
                active.sendMsg(template.default, `当前正在与BOSS战斗中.请保持血量健康`)
                return;
            }
            active.sendMsg(template.default, `当前正在参与其他战斗中.`)
            return;
        }
        this.battles.join(this.bossUnit, group.主场);
        this.battles.join(active, group.客场);
        this.battles.start();
        this.battles.setEndCall((a, b) => { this.onBattleEnd(a, b) })
        this.battles.setOutEndCall((a, b) => { this.onBattleOutEnd(a, b) })
        this.battles.setKillCall((a, b, c, d) => { this.onBattleKill(a, b, c, d) })
        this.battles.setRoundCall((a, b) => { this.onBattleRound(a, b) })
        active.sendMsg(template.default, `[${active.name}]战斗开始!接下来你可以直接发送技能名称来决定下回合释放技能!回合倒计时:${this.battles.getRoundTime()}秒`)
    }
}